import { Request, Response } from 'express';
import { spawn } from 'child_process';
import path from 'path';

// 执行Python脚本的辅助函数
const executePythonScript = (scriptName: string, args: string[] = []): Promise<string> => {
  return new Promise((resolve, reject) => {
    const pythonProcess = spawn('python', [
      path.join(__dirname, '../../../question_generator.py'),
      scriptName,
      ...args
    ]);

    let result = '';
    let error = '';

    pythonProcess.stdout.on('data', (data) => {
      result += data.toString();
    });

    pythonProcess.stderr.on('data', (data) => {
      error += data.toString();
    });

    pythonProcess.on('close', (code) => {
      if (code !== 0) {
        reject(new Error(`Python脚本执行失败: ${error}`));
      } else {
        resolve(result.trim());
      }
    });
  });
};

// 基础对话
export const chat = async (req: Request, res: Response) => {
  try {
    const { message } = req.body;
    const response = await executePythonScript('chat', [message]);
    res.json({ response });
  } catch (error: any) {
    console.error('对话失败:', error);
    res.status(500).json({
      code: 1,
      message: '对话失败: ' + (error.message || '未知错误')
    });
  }
};

// 处理文档生成题目
export const processDocument = async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      throw new Error('未上传文件');
    }

    const response = await executePythonScript('process_document', [req.file.path]);
    res.json({ response });
  } catch (error: any) {
    console.error('处理文档失败:', error);
    res.status(500).json({
      code: 1,
      message: '处理文档失败: ' + (error.message || '未知错误')
    });
  }
};

// 生成特定类型题目
export const generateQuestions = async (req: Request, res: Response) => {
  try {
    const { question_type, count, difficulty, context, file_path } = req.body;
    
    console.log('收到题目生成请求:', { question_type, count, difficulty, context, file_path });
    
    // 如果有文件路径，使用generate_questions命令并传递file_path参数
    if (file_path) {
      console.log('处理文档题目生成:', file_path);
      const args = [
        file_path,                    // file_path
        question_type || '',          // question_type
        (count || 5).toString(),      // count
        difficulty || '中等',         // difficulty
        context || ''                 // context
      ];
      console.log('文档题目生成参数:', args);
      const response = await executePythonScript('generate_questions', args);
      res.json({ response });
    } else {
      // 普通题目生成
      const args = [
        '',                           // 空字符串表示没有file_path
        question_type || '',          // question_type
        (count || 5).toString(),      // count
        difficulty || '中等',         // difficulty
        context || ''                 // context
      ];
      console.log('普通题目生成参数:', args);
      const response = await executePythonScript('generate_questions', args);
      res.json({ response });
    }
  } catch (error: any) {
    console.error('生成题目失败:', error);
    res.status(500).json({
      code: 1,
      message: '生成题目失败: ' + (error.message || '未知错误')
    });
  }
}; 